#!/usr/bin/env node

import { execSync } from 'child_process';
import { readdirSync, statSync } from 'fs';
import { join } from 'path';

const packagesDir = join(process.cwd(), 'packages');
const packages = readdirSync(packagesDir).filter((file) => {
  const fullPath = join(packagesDir, file);
  return statSync(fullPath).isDirectory() && 
         readdirSync(fullPath).includes('package.json');
});

console.log('开始使用 Rollup 构建 packages...');

for (const pkg of packages) {
  try {
    console.log(`\n构建包: ${pkg}`);
    const pkgPath = join(packagesDir, pkg);
    
    // 检查是否存在 rollup.config.js
    const hasRollupConfig = readdirSync(pkgPath).includes('rollup.config.js');
    if (!hasRollupConfig) {
      console.log(`跳过 ${pkg}，未找到 rollup.config.js`);
      continue;
    }
    
    // 运行 rollup 构建
    execSync(`cd ${pkgPath} && npm run build:rollup`, { stdio: 'inherit' });
    console.log(`✅ ${pkg} 构建完成`);
  } catch (error) {
    console.error(`❌ ${pkg} 构建失败:`, error.message);
    process.exit(1);
  }
}

console.log('\n所有包均已使用 Rollup 构建完成！');